# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 21:16:41 2018

@author: Administrator
"""
print('acrosssubjectcorrelate--acrosssubjectcorrelate--acrosssubjectcorrelate')
import os
import glob
import sys
from ..origin import Shell_script
from ..log import Log_make

#%%
    
class Across_subject_correlate(Shell_script):
    #作用原理：如对30个subjectPET_z map和CBF_z map进行aross subject correlate
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    masked_str = r'_masked'
    all_str = r'_all'
    def __init__(self,input_list):
        print('Across_subject_correlate-Across_subject_correlate-Across_subject_correlate')
        print('input_list:',input_list)
        if len(input_list) != 3 :
            raise Exception("the number of elements of input_list is not equal to 3")
        super().__init__(input_list)
        
    def initialize_input_list(self,input_list):
        
        #test if the input_list has four parameters
        ##########################################################################重新整理传入参数
        self.group1_dirpath = input_list[0][0]
        self.group2_dirpath = input_list[0][1]
        self.mask_filepath = input_list[0][2]
        self.output_dirpath = input_list[0][3]
        self.column_name_list = input_list[1]
        self.tag = input_list[2]
        
    def concat_inputs(self):
        
        print('search_path:',self.group1_dirpath+self.os_sep+self.star+self.suffix) 
        print('search_path:',self.group2_dirpath+self.os_sep+self.star+self.suffix)
        self.group1_filepaths = glob.glob(self.group1_dirpath+self.os_sep+self.star+self.suffix)
        self.group2_filepaths = glob.glob(self.group2_dirpath+self.os_sep+self.star+self.suffix)
        self.group1_filepaths.sort()
        self.group2_filepaths.sort()
        print('group1_filepaths:',self.group1_filepaths)
        print('group2_filepaths:',self.group2_filepaths)
        
        if len(self.group1_filepaths) != len(self.group2_filepaths):
            raise Exception("the number of file of group1 is different from that of group2 ")
        self.fileamount = len(self.group1_filepaths)
        
        #the code below is used to concatenate all the filepath into one string which will be used as parameter by the '3dTcat' command
        self.group1_filepaths_str = ''.join([i + self.space  for i in self.group1_filepaths])
        self.group2_filepaths_str = ''.join([i + self.space  for i in self.group2_filepaths])
        
        # the two parameters bolow is used to label the concatenated nii file
        self.group1_label_str = os.path.split(os.path.split(self.group1_filepaths[0])[0])[1]
        self.group2_label_str = os.path.split(os.path.split(self.group2_filepaths[0])[0])[1]
        print('self.group1_label_str:',self.group1_label_str)
        print('self.group2_label_str:',self.group2_label_str)
        
        ## the two parameters bolow is used to label the coeff nii file and the dirname which contains the coeff nii file
        self.label_str = self.tag.replace(self.os_sep,self.underline)
        self.cross_modality_dirpath = self.output_dirpath + self.os_sep + self.label_str
        if not os.path.exists( self.cross_modality_dirpath):
            os.makedirs( self.cross_modality_dirpath)
        self.group1_all_filepath = self.output_dirpath + self.os_sep + self.label_str + os.sep + \
                                                                    self.group1_label_str + self.all_str + self.suffix
        self.group2_all_filepath = self.output_dirpath + self.os_sep + self.label_str + os.sep + \
                                                                    self.group2_label_str + self.all_str + self.suffix
        print(r'self.group1_all_filepath:',self.group1_all_filepath)
        print(r'self.group2_all_filepath:',self.group2_all_filepath)
        self.coeff_filepath = self.cross_modality_dirpath + self.os_sep + self.group1_label_str + self.linkline + \
                                                                                self.group2_label_str + self.suffix
        print(r'self.coeff_filepath:',self.coeff_filepath)
        self.coeff_masked_filepath = self.cross_modality_dirpath + self.os_sep + self.group1_label_str + self.linkline + \
                                                                        self.group2_label_str + self.masked_str + self.suffix
        print(r'self.coeff_masked_filepath:',self.coeff_masked_filepath)
    def concat_script(self):
        #特有的文件路径
        
        #cmd_1的内容：3dTcat -prefix   
        self.cmd_1 =  r'3dTcat -prefix ' + self.group1_all_filepath + self.space + self.group1_filepaths_str 
        self.cmd_1a =  r'3dTcat -prefix ' + self.group2_all_filepath + self.space + self.group2_filepaths_str
        
        #cmd_2的内容：3dTcorrelate -prefix subj_240_9_BOLD_tcat.nii.gz   setX  setY
        self.cmd_2 = r'3dTcorrelate -pearson -polort -1  -prefix ' + self.coeff_filepath  + self.space + self.group1_all_filepath + \
                                                                       self.space + self.group2_all_filepath
                                                
        #cmd_3的内容：3dcalc -a -b mask  -expr 'a*b'
        self.cmd_3 = r'3dcalc -a   ' + self.coeff_filepath + ' -b ' + self.mask_filepath + ' -expr \'a*b\'' + \
                                                                    ' -prefix ' + self.coeff_masked_filepath
        
        self.shell_script = self.cmd_1 + self.cmd_sep + self.cmd_1a + self.cmd_sep + self.cmd_2 + self.cmd_sep + self.cmd_3


#%%
        
class Multi_across_subject_correlate(Log_make):
    #作用原理：如对30个subjectPET_z map和CBF_z map和 ALFF_z和fALFF_z排列组合，然后调用aross subject correlate
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    def __init__(self,input_list):
#       print('input_list:',input_list)
#       print('numb of input_list:',len(input_list))
        if len(input_list) != 2 :
            raise Exception("the number of elements of input_list is not equal to 2")
        grouppath_dict = input_list[0]
        column_name_list = input_list[1]
        i = 0
        #grouppath_dict is showed at the end of this script
        for item in grouppath_dict.keys():
            print('item:',item)
            print('grouppath_dict[item]:',grouppath_dict[item])
            output_dirpath = grouppath_dict[item][3]
            outcome = Across_subject_correlate([grouppath_dict[item],column_name_list,item])
            if outcome.stdout_err != None:
                #之所以这样判断是因为afni下面的如3dcalc等命令的stdout stderr非常特殊。详见key值指向的函数。
                print('errorerrorerrorerrorerrorerrorerror')
                print('stdout_err:',outcome)
                print('i:',i)
                medi = output_dirpath + os.sep + item
                if not os.path.exists( medi):
                    os.makedirs( medi)
                err_log_path =  medi + os.sep + sys._getframe().f_code.co_name + '_err_log.txt'
                self.shell_err_log_write(err_log_path,item,outcome.stdout_err,grouppath_dict[item],i)
                #previous_filename,present_filename这两个参数是不对的。
                i = i + 1
        
#%%下面是使用Multi_across_subject_correlate的example
        
#zpet_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/PET_processing/PET_normalised_resliced_smoothed_Zstandardized'
#zcbf_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/CBF_clear_background_SN_SR_SSM-6_z'
#zfalff_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/fALFF_z'
#zalff_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/ALFF_Z'
#zreho_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/ReHo_z'
#cbf_groupmask_filepath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/make_mask_before_z_standardize/sws_CBF_26_intersect_mask.nii'
#bold_groupmask_filepath = r''
#pet_groupmask_filepath = r''
#mni_brainmask_filepath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/make_mask_before_z_standardize/BrainMask.nii'
#multi_modalitymask_filepath = r''
#output_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609'
#column_name_list = ['coeff','pvalue','modalities']
#
#
#
#grouppath_dict = {'PET/CBF':[zpet_dirpath,zcbf_dirpath,cbf_groupmask_filepath,output_dirpath],\
#                 'PET/fALFF':[zpet_dirpath,zfalff_dirpath,mni_brainmask_filepath,output_dirpath],\
#                 'PET/ALFF':[zpet_dirpath,zalff_dirpath,mni_brainmask_filepath,output_dirpath],\
#                 'PET/ReHo':[zpet_dirpath,zreho_dirpath,mni_brainmask_filepath,output_dirpath],\
#                 'CBF/fALFF':[zcbf_dirpath,zfalff_dirpath,cbf_groupmask_filepath,output_dirpath],\
#                 'CBF/ALFF':[zcbf_dirpath,zalff_dirpath,cbf_groupmask_filepath,output_dirpath],\
#                 'CBF/ReHo':[zcbf_dirpath,zreho_dirpath,cbf_groupmask_filepath,output_dirpath] }
#
#
#Multi_across_subject_correlate([grouppath_dict,column_name_list])